package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Fxz
 * @version 1.0
 * @date 2021-08-23 16:58
 */
public class StaticResourceUtil {

    /**
     * 获取静态资源文件的绝对路径
     *
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path) {
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\", "/") + path;
    }

    /**
     * 读取静态资源输入流 通过输出流输出
     *
     * @param fileInputStream
     * @param outputStream
     */
    public static void outputStaticResource(InputStream fileInputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = fileInputStream.available();
        }
        int resourceSize = count;

        //输出http请求头
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());
        //输出具体内容 先读取出内容
        //已经读取的内容长度
        int written = 0;
        //计划每次缓冲的长度
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];

        while (written < resourceSize) {
            if (written + byteSize > resourceSize) {
                byteSize = resourceSize - written;
                bytes = new byte[byteSize];
            }
            fileInputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();

            written += byteSize;
        }
    }
}
